package mamikeji.liaowa.ui.activity.article;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.ArticleTypeBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.ArticleTypeAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class ArticleTypeActivity extends BaseActivity {
    private static final String TAG = "ArticleTypeActivity";
    private static final int TAG_CIRCLE = 1001;
    List<ArticleTypeBean.DataEntity> mList = new ArrayList<>();
    private ArticleTypeAdapter article_detailsAdapter;
    private ListView listView_article_type;
    private PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout_article_type;
    private MultiStateView multiStateView_article_type;

    Boolean bool_circle_refresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_type);
        getBase();
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bool_circle_refresh){
                    setResult(RESULT_OK, new Intent());
                }
                finish();
            }
        });
        setTitleName(R.string.dayrecommend_type);

        ptrlDownRefreshFrameLayout_article_type = (PtrlDownRefreshFrameLayout) findViewById(R.id.ptrlDownRefreshFrameLayout_article_type);
        listView_article_type = (ListView) findViewById(R.id.listView_article_type);
        article_detailsAdapter = new ArticleTypeAdapter(mList, this);
        listView_article_type.setAdapter(article_detailsAdapter);

        multiStateView_article_type = (MultiStateView) findViewById(R.id.multiStateView_article_type);

        initdate();

        ptrlDownRefreshFrameLayout_article_type.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView_article_type, header);
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                initdate();
            }
        });
        listView_article_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(ArticleTypeActivity.this,Article_ListActivity.class);
                intent.putExtra("category",mList.get(i).getId()+"");
                intent.putExtra("category_name",mList.get(i).getName()+"");
                startActivityForResult(intent, TAG_CIRCLE);
            }
        });

        multiStateView_article_type.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_article_type.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        initdate();
                    }
                });
    }

    /**
     * 获取文章类别
     */
    private void initdate() {
        String url = HttpApi.ROOT_PATH + HttpApi.ARTICLE_TYPE+"?usercode="+ ForPreference.getString(ForContents.USER_CODE);
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.ARTICLE_TYPE_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.getMsg(url, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_article_type.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                ptrlDownRefreshFrameLayout_article_type.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                Log.e(TAG, response);
                ptrlDownRefreshFrameLayout_article_type.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ArticleTypeBean articleTypeBean = new Gson().fromJson(response,ArticleTypeBean.class);
                        if (articleTypeBean.getData() != null){
                            if (articleTypeBean.getData().size() > 0){
                                mList = articleTypeBean.getData();
                                article_detailsAdapter.setList(mList);
                                multiStateView_article_type.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            }else {
                                multiStateView_article_type.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }
                        } else {
                            multiStateView_article_type.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    }else {
                        multiStateView_article_type.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                bool_circle_refresh = true;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (bool_circle_refresh){
                setResult(RESULT_OK, new Intent());
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("撩娃宝典");
        MobclickAgent.onResume(this);       //开始统计时长
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("撩娃宝典");
        MobclickAgent.onPause(this);       //结束统计时长
    }
}
